local services_config = require "services"

local _M = {}
_M._VERSION = "1.0"

-- 共享字典，用于缓存健康的后端服务
local health_cache = ngx.shared.service_health_cache

-- 健康检查函数
function _M.health_check(backend_url, health_path)
    local http = require "resty.http"
    local httpc = http.new()
    
    httpc:set_timeout(3000)  -- 3秒健康检查超时
    
    local res, err = httpc:request_uri(backend_url .. health_path, {
        method = "GET",
        headers = {
            ["User-Agent"] = "OpenResty-Health-Check/1.0"
        }
    })
    
    if res and (res.status == 200 or res.status == 404) then
        return true
    end
    
    ngx.log(ngx.WARN, "Health check failed for ", backend_url, ": ", err)
    return false
end

-- 获取健康的后端服务
function _M.get_healthy_backend(service_name)
    ngx.log(ngx.INFO, "Getting healthy backends for service: ", service_name)
    local service = services_config.services[service_name]
    if not service then
        return nil, "Service not found: " .. service_name
    end    
    
    return  service.endpoints, nil
end

-- 负载均衡：随机选择后端
function _M.select_backend(service_name)
    local backends, err = _M.get_healthy_backend(service_name)
    if not backends then        
        ngx.log(ngx.ERR, "Failed to get healthy backends: ", err)
        return nil, err
    end
    
    math.randomseed(ngx.now() * 1000)
    local index = math.random(1, #backends)
    ngx.log(ngx.INFO, "Selected backend index: ", index, " for service: ", service_name, " from ", #backends, " healthy backends")
    return backends[index]
end

-- 解析请求路径，提取服务名和剩余路径
function _M.parse_request_path(path)
    local service_name, remaining_path = path:match("^/([^/]+)(.*)$")
    if not service_name then
        return nil, nil, "Invalid path format"
    end
    
    -- 如果剩余路径为空，设置为根路径
    if remaining_path == "" then
        remaining_path = "/"
    end
    
    return service_name, remaining_path
end

return _M